package com.zzuli.yxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzuli.yxy.entity.Employee;
import com.zzuli.yxy.entity.LoginUser;
import com.zzuli.yxy.mapper.EmployeeMapper;
import com.zzuli.yxy.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * UserDetailsService 接口有一个默认的实现类 InMemoryUserDetailsManager
 * 它根据用户名会去内存查用户信息和权限信息并且封装到UserDetails
 * 我们要自己实现这个接口然后去查数据库，封装返回数据
 * @auther pony
 * @create 2023-03-05 18:57
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //1、查询用户信息
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,s);
        Employee employee = employeeMapper.selectOne(qw);
        if (Objects.isNull(employee)){
            throw new RuntimeException("用户名或者密码错误！");
        }
        //2、查询对应的权限信息
        List<String> list = menuMapper.selectPermsByEmployeeId(employee.getId());
        // 3、将用户信息封装成UserDetails类并且返回，UserDetails是一个接口，要自己写一个实现类
        return new LoginUser(employee, list);
    }
}
